#include <stdio.h>
#include <math.h>

//编译：gcc -o run_curve_fitting_v1 curve_fitting_v1.c -lm

// 最小二乘法拟合二次曲线
void leastSquaresFit(double points[3][2], double *coefficients) {
    double sumX = 0, sumY = 0, sumX2 = 0, sumXY = 0;

    // 计算数据点的和
    for(int i = 0; i < 3; ++i) {
        double x = points[i][0];
        double y = points[i][1];
        sumX += x;
        sumY += y;
        sumX2 += x * x;
        sumXY += x * y;
    }

    // 计算平均值
    double meanX = sumX / 3;
    double meanY = sumY / 3;
    double meanX2 = sumX2 / 3; 

    // 计算系数
    double ssX = sumX2 - 3 * meanX * meanX;
    double ssY = sumY - 3 * meanY;
    double ssXY = sumXY - 3 * meanX * meanY;

    // 计算系数
    coefficients[0] = ((ssXY - meanX * meanY) / (3 * meanX2)) * 100000; // a
    coefficients[1] = ((meanX * meanY - ssXY) / (3 * meanX)) * 100000; // b
    coefficients[2] = meanY * 100000; // c

    printf(">>> 计算参数：%f %f %f \r\n",coefficients[0],coefficients[1],coefficients[2]);
}

int main() {
    // 提供的三个点
    double points[3][2] = {
        {35658,9.808}, // 点1
        {67369,15.67}, // 点2
        {78092,19.261999}  // 点3
    };

    // 存储系数
    double coefficients[3] = {0, 0, 0};

    // 执行最小二乘拟合
    leastSquaresFit(points, coefficients);

    // 打印结果
    printf(">>> y = %fx^2 + %fx + %f \n", coefficients[0], coefficients[1], coefficients[2]);

    float x = 166387.0;
    printf("x=%f so y=%f \r\n",x,((coefficients[0]*pow(x,2))+(coefficients[1]*x)+coefficients[2])/100000);

    return 0;
}

